<?php /* УТФ-8:fix */

class SPImodel__adv__front extends SPImodel__adv
{
    public function select( $adv_position, $select_mode, $count )
    {
        switch( $select_mode )
        {
            default:
            case 'random':
            {
                $q_order = " ORDER BY RANDOM() ";
                $count   = max( 1, (int) $count );
                break;
            }

            case 'all':
            {
                $q_order = " ORDER BY name ASC, id ASC ";
                $count   = null;
                break;
            }
        }


        $query =    " SELECT * "
               .      " FROM ".SPIcfg::$store['table:adv']
               .     " WHERE position = '" . addslashes( $adv_position ) . "' "
               .       " AND workstatus=1 "
               . $q_order
               . ( $count ? " LIMIT {$count} " : '' )
               ;

        return SPIstore::I()->query( $query );
    }

    public function inc_counter( $field, $ids )
    {
        if( in_array( $field, array( 'click_count', 'showed_count' ) ) === false )
        {
            return false;
        }

        if( is_array( $ids ) === false )
        {
            $ids = array( $ids );
        }
        elseif( count( $ids ) == 0 )
        {
            return false;
        }

        foreach( $ids as $k=>$v )
        {
            $ids[$k] = (int) $v;
        }

        $query =   " UPDATE ".SPIcfg::$store['table:adv']
               .      " SET {$field} = {$field}+1 "
               .    " WHERE id IN( " . join( ',', $ids ) . " ) "
               ;

        return SPIstore::I()->query( $query )->close();
    }

    public function get_by_id( $item_id )
    {
        $query =    " SELECT * "
               .      " FROM ".SPIcfg::$store['table:adv']
               .     " WHERE id=" . (int) $item_id
               .       " AND workstatus=1 "
               ;

        return SPIstore::I()->query( $query )->fetch_and_close();
    }
}
